<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="isDealName" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              :scope-authority="true"
              parameters="deal"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否用印')" prop="isSeal">
            <el-radio-group v-model="form.isSeal">
              <el-radio-button
                v-for="dict in isSealOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('会议类型')" prop="meetingType">
            <el-select v-model="form.meetingType" filterable :placeholder="$t('会议类型')">
              <el-option
                v-for="dict in meetingTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('会议时间')" prop="meetingTime">
            <DatePicker v-model="form.meetingTime" :placeholder="$t('会议时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('我方参会人员')" prop="ourParticipants">
            <UserSelect
              v-model="form.ourParticipants"
              multiple
              :placeholder="$t('我方参会人员')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('其他参会人员')" prop="otherParticipants">
            <el-input v-model="form.otherParticipants" :maxlength="120" show-word-limit :placeholder="$t('其他参会人员')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('三会内容')" prop="emailContent">
            <EditorTxt v-model="form.emailContent" :height="400" :placeholder="$t('三会内容')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('议案列表') }}</span>
      </div>
      <el-table :data="form.dealMeetingBillList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('议题内容')" align="center" prop="topicsContent">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('议题内容') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealMeetingBillList.' + scope.$index + '.topicsContent'" :rules="rules.topicsContent">
              <el-input v-model="scope.row.topicsContent" type="textarea" :autosize="{ maxRows: 5 }" :maxlength="125" show-word-limit :placeholder="$t('议题内容')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('我方表决')" align="center" prop="ourVote">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('我方表决') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealMeetingBillList.' + scope.$index + '.ourVote'" :rules="rules.ourVote">
              <dict-select
                v-model="scope.row.ourVote"
                dictionary="bill_vote"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('说明')" align="center" prop="remark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" type="textarea" :autosize="{ maxRows: 5 }" :maxlength="2000" show-word-limit :placeholder="$t('说明')" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否为重大事项')" prop="areMatter" align="center" width="150">
          <template slot-scope="scope">
            <el-select v-model="scope.row.areMatter" :placeholder="$t('是否为重大事项')" clearable>
              <el-option
                v-for="dict in areMatterOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column v-if="form.actStatus === 'W'" :label="$t('最终结论')" align="center" prop="finalConclusion">
          <template slot-scope="scope">
            <dict-select
              v-model="scope.row.finalConclusion"
              disabled
              dictionary="final_ourVote"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.areMatter === 'Y'" size="mini" type="text" :disabled="false" icon="el-icon-view" @click="viewMatterHandle(scope.row, scope.$index)">{{ $t('重大事项信息') }}</el-button>
            <el-button v-if="!otherBtnHide || !useProcess" size="mini" type="text" icon="el-icon-delete" @click="delBill(scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide || !useProcess" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addBill">{{ $t("添加") }}</el-button>
      </div>
      <!--用印明细-->
      <div v-if="form.isSeal === 'Y'" style="margin-top:8px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('用印明细') }}</span>
        </div>
        <el-table :data="form.oaSealDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体类型')" align="center" min-width="180">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMainType'" :rules="oaSealDetailListRules.investMainType">
                <dictSelect
                  v-model="scope.row.investMainType"
                  :clearable="true"
                  dictionary="main_body_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体')" align="center" min-width="350">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMain'" :rules="oaSealDetailListRules.investMain">
                <MainBodySelect
                  v-model="scope.row.investMain"
                  :parameters="scope.row.investMainType"
                  @change="duplicateVerificationSubject"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印类型')" align="center" min-width="300">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.sealType'" :rules="oaSealDetailListRules.sealType">
                <el-select
                  v-model="scope.row.sealType"
                  multiple
                  :placeholder="$t('用印类型')"
                >
                  <el-option
                    v-for="dict in sealTypeDict"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" min-width="300">
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.remark'" :rules="oaSealDetailListRules.remark">
                <el-input v-model="scope.row.remark" type="textarea" :autosize="{ maxRows: 5 }" :maxlength="2000" show-word-limit :placeholder="$t('备注')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide || !useProcess" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:meeting:edit']" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide || !useProcess" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <FileTable :list.sync="form.fileList" data-type="deal_meeting" has-permi="deal:meeting" :business-id="autoBusinessId($route.query.id ? $route.query.id : form.dealId, form)" :btn-show="!otherBtnHide || !useProcess" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--使用流程 保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="useProcess" ref="formBtn" :bus-data="form" :btn-hide="btnHide" has-permi="deal:meeting" :menu-key="menuKey" />
      <!--未使用流程：保存 取消按钮-->
      <save-btn v-else has-permi="deal:meeting" :btn-hide="btnHide" />
    </div>

    <el-dialog :title="$t('重大事项')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <deal-matters-form ref="dealMattersForm" :btn-meeting-hide="btnHide" visible ref-type="meeting" @meeting="confirmMatter" />
    </el-dialog>
  </div>
</template>

<script>
    import { saveDealMeeting, getDealMeeting } from '@/api/deal/meeting/dealMeeting'
    import { getDealName } from '@/api/base/deal/dealBase'
    import dealMattersForm from '@/views/deal/matters/dealMattersForm'
    import { deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
    import MainBodySelect from '@/components/MainBodySelect'
    import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
    import EditorTxt from '@/components/Editor/index.vue'
    export default {
      components: {
        EditorTxt,
        dealMattersForm,
        MainBodySelect
      },
        data() {
            return {
                // 菜单标识
                menuKey: 'deal_meeting',
               useProcess: false,
                // 会议类型 字典meeting_type字典
                meetingTypeOptions: [], // 表单参数
                areMatterOptions: [],
                // 是否用印
                isSealOptions: [],
                // 用印类型
                sealTypeDict: [],
                form: {
                  oaSealDetailList: [],
                  fileList: []
                },
                // 是否隐藏保存按钮
                btnHide: false,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 表单校验
                rules: {
                meetingType: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], ourVote: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], meetingIssue: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], actTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], topicsContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], isSeal: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], dealId: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ] },
                oaSealDetailListRules: {
                  investMainType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  investMain: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  sealType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: false,
                formOpen: false,
                billIndex: 0,
              // 是否展示项目名称
              isDealName: this.$attrs.parameter && this.$attrs.parameter.quick && this.$attrs.parameter.quick === 'true'
            }
        },
        created() {
          // 查询是否配置流程
            this.getUseProcess()
            this.getDicts('meeting_type').then(response => {
                this.meetingTypeOptions = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
              this.areMatterOptions = response.data
              this.isSealOptions = response.data
            })
            this.getDicts('seal_type').then(response => {
              this.sealTypeDict = response.data
            })
            this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealMeeting(data.id).then(response => {
                        this.form = response.data
                        this.loading = false
                    })
                } else {
                    this.reset()
                    // 默认带出流程中必须要传的附件
                    if (data) {
                      this.form.fileList = data.fileList
                    }
                  this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                dealId: this.$route.query.id,
                companyId: this.$route.query.companyId,
                meetingType: undefined,
                meetingTime: undefined,
                ourParticipants: undefined,
                otherParticipants: undefined,
                meetingIssue: undefined,
                meetingDecision: undefined,
                actId: undefined,
                actStatus: undefined,
                isSeal: 'N',
                oaSealDetailList: [],
                fileList: [],
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                dealMeetingBillList: [],
                  emailContent: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm(type) {
              // 关闭form页面遮罩层
              this.loading = false
              if (type !== 'actSave') {
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
              }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                    let flag = true
                    if (this.form.isSeal === 'Y') {
                      if (this.form.oaSealDetailList.length === 0) {
                        this.msgError(this.$t('至少添加一条用印明细!'))
                        flag = false
                      }
                    }
                    // 验证数据
                    if (valid && flag) {
                      // 弹出遮罩层
                      this.loading = true
                      // 保存方式，如果值为actSave则是从流程表单中进行的保存，默认将delFlag 设置为2,审批通过后在更新为0
                      this.form.saveType = type
                      this.form.useProcess = this.useProcess
                      // 新增数据时 如果没有配置流程，则将审批状态设置为审批完成
                      if (!this.useProcess && !this.form.id) {
                        this.form.actStatus = 'W'
                      }
                      // 保存数据
                      saveDealMeeting(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                            this.form.id = response.data.id
                            // 启动流程
                            this.startProcess(response.data.id)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm(type)
                          }
                          resolve(response.data.id)
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject(response)
                        }
                      }).catch(() => {
                        this.loading = false
                      })
                    } else {
                      this.locationError(document)
                      reject()
                    }
                })
              })
           },
            // 会议类型 字典meeting_type字典翻译
            meetingTypeFormat(meetingType) {
              return this.selectDictLabel(this.meetingTypeOptions, meetingType)
            },
            // 启动流程
           startProcess: async function(dataId) {
               const dealName = await getDealName(this.$route.query.id ? this.$route.query.id : this.form.dealId)
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '「' + dealName + '」' + ':' + this.form.actTitle
               // 业务表名
               processData.dataTable = 'deal_meeting'
               // 业务ID
               processData.dataId = dataId
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/meeting/dealMeetingForm'
               processData.viewPath = '@/views/deal/meeting/dealMeetingView'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          delBill(index) {
              this.form.dealMeetingBillList.splice(index, 1)
          },
          addBill() {
            const row = {
             id: undefined,
             meetingId: undefined,
             topicsContent: undefined,
             ourVote: undefined,
             remark: undefined,
             dealMatters: {
                id: undefined,
                dealId: undefined,
                companyId: undefined,
                itemName: undefined,
                happenTime: undefined,
                itemType: undefined,
                handle: 'N',
                handleTime: undefined,
                handleMode: undefined,
                handleDesc: undefined,
                itemDesc: undefined,
                isSeal: 'N',
                oaSealDetailList: [],
                fileList: [],
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                actId: undefined,
                actStatus: undefined
              }
            }
            if (!(this.form.dealMeetingBillList instanceof Array)) {
              this.$set(this.form, 'dealMeetingBillList', [])
            }
            this.$nextTick(() => {
              this.form.dealMeetingBillList.push(row)
            })
          },
          viewMatterHandle(row, index) {
              this.formOpen = true
              this.billIndex = index
              this.$nextTick(() => {
                if (row.dealMatters) {
                  row.dealMatters['actTitle'] = this.$t('三会管理') + ':' + row.topicsContent
                  row.dealMatters['itemName'] = row.topicsContent
                } else {
                  row.dealMatters = {
                    actTitle: this.$t('三会管理') + ':' + row.topicsContent,
                    itemName: row.topicsContent
                  }
                }
                if (this.btnHide) {
                  this.$refs.dealMattersForm.meetingToSaveBtn = false
                }
                row.dealMatters['dealId'] = this.form.dealId
                this.$refs.dealMattersForm.init(row.dealMatters)
                // this.$refs.dealMattersForm.isDealName = true
                this.$refs.dealMattersForm.isDealEdit = true
                if (row.dealMatters.id === undefined || row.dealMatters.id === '' || row.dealMatters.id === undefined) {
                  this.$refs.dealMattersForm.form.actTitle = this.form.actTitle
                }
                // 补充用印信息
                if (this.form.isSeal === 'Y' && (this.isEmpty(row.dealMatters.id) || row.dealMatters.id === '') && this.isEmpty(this.$refs.dealMattersForm.form.oaSealDetailList)) {
                  this.$refs.dealMattersForm.form.isSeal = 'Y'
                  this.$refs.dealMattersForm.form.oaSealDetailList = JSON.parse(JSON.stringify(this.form.oaSealDetailList))
                }
              })
          },
          confirmMatter(matter) {
              this.$set(this.form.dealMeetingBillList[this.billIndex], 'dealMatters', matter)
          },
          // 用印明细
          addPayment() {
            const row = {
              id: undefined,
              investMainType: '',
              investMain: '',
              sealType: '',
              remark: ''
            }
            if (!(this.form.oaSealDetailList instanceof Array)) {
              this.$set(this.form, 'oaSealDetailList', [])
            }
            this.$nextTick(() => {
              this.form.oaSealDetailList.push(row)
            })
          },
          // 删除用印明细
          delHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return deleteOaSealDetail(id)
                }).then(() => {
                this.form.oaSealDetailList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaSealDetailList.splice(index, 1)
            }
          },
          // 用印主体校验重复
          duplicateVerificationSubject(val) {
            this.$nextTick(() => {
              if (this.form.oaSealDetailList !== undefined && this.form.oaSealDetailList !== null) {
                var count = 0
                this.form.oaSealDetailList.some((item, index) => {
                  if (item.investMain === val) {
                    if (count > 0) {
                      this.form.oaSealDetailList.splice(index, 1)
                      this.msgError(this.$t('该主体已存在'))
                      return true
                    }
                    count++
                  }
                })
              }
            })
          },
          // 获取是否使用流程
          getUseProcess() {
            getMenuProcess('deal_meeting').then(response => {
              this.useProcess = !!response.data
            })
          }
        }
    }
</script>
<style lang="scss" scoped>
/deep/.avatar-uploader.quill-img{
  display: none;
}
</style>
